#include "EventLoop.h"

EventLoop::EventLoop(int work_num /* = 0 */)
    : iocp_(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0))
    , cur_id_(std::this_thread::get_id())
{
    Start(work_num);
}

EventLoop::~EventLoop()
{
    Stop();
}

void EventLoop::Start(int work_num)
{
    if (work_num == 0) {
        SYSTEM_INFO sysInfo;
        GetSystemInfo(&sysInfo);
        work_num = sysInfo.dwNumberOfProcessors * 2;
    }

    for (int i = 0; i < work_num; i++) {
        workers_.push_back(std::thread(
            std::bind(&EventLoop::WorkerProc, this)));
    }
}

void EventLoop::Stop()
{
    if (iocp_ != INVALID_HANDLE_VALUE) {
        CloseHandle(iocp_);
        iocp_ = INVALID_HANDLE_VALUE;
    }

    ThreadArrayIte iter = workers_.begin();
    for (; iter != workers_.end(); ++iter)
        iter->join();
}

void EventLoop::WorkerProc()
{
    DWORD bytes = 0;
    ULONG_PTR comkey = NULL;
    LPOVERLAPPED op = NULL;

    while (true)
    {
        BOOL ret = GetQueuedCompletionStatus(iocp_, &bytes, )

    }

}

bool EventLoop::IsSameThread()
{
    return cur_id_ == std::this_thread::get_id();
}